package com.ruoyi.door.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.ruoyi.door.domain.DoorHouse;
import com.ruoyi.door.service.DoorHouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component("doorCalculateEndDateJob")
@Slf4j
public class DoorCalculateEndDateJob {
    @Autowired
    private EasyEntityQuery easyEntityQuery;
    
    @Autowired
    private DoorHouseService doorHouseService;

    public void ryNoParams() {
        log.info("开始执行房产余额扣减和到期时间计算任务");
        
        // 获取当前月份1号
        Date firstDayOfMonth = DateUtil.beginOfMonth(new Date());
        
        // 查询 startDate 小于当前月份1号的房产
        List<DoorHouse> houseList = easyEntityQuery.queryable(DoorHouse.class)
                .where(d -> d.startDate().lt(firstDayOfMonth))
                .toList();
        
        if (CollectionUtil.isEmpty(houseList)) {
            log.info("没有需要处理的房产");
            return;
        }
        
        log.info("查询到需要处理的房产数量: {}", houseList.size());
        
        int successCount = 0;
        int failCount = 0;
        
        // 遍历需要扣费的房产
        for (DoorHouse doorHouse : houseList) {
            // 调用封装的服务方法更新房产到期时间
            boolean success = doorHouseService.updateHouseEndDate(doorHouse);
            
            if (success) {
                successCount++;
            } else {
                failCount++;
            }
        }
        
        log.info("房产余额扣减和到期时间计算任务执行完成，成功: {}，失败: {}", successCount, failCount);
    }
}
